package flag

import (
	"context"
	"fmt"
	"github.com/urfave/cli/v3"
	"go.uber.org/zap"
	"os"
	"server/global"
)

// 定义 CLI 标志，用于不同操作的命令行选项

var (
	sqlFlag = &cli.BoolFlag{
		Name:  "sql",
		Usage: "Initializes the structure of the MySQL database table.",
	}
	esFlag = &cli.BoolFlag{
		Name:  "es",
		Usage: "Initializes the elasticsearch index.",
	}
	adminFlag = &cli.BoolFlag{
		Name:  "admin",
		Usage: "Creates an administrator using the name, email and address specified in the config.yaml file.",
	}
)

// Run 执行基于命令行标志的相应操作
// 它处理不同的标志，执行相应操作，并记录成功或错误的消息
func Run(ctx context.Context, cmd *cli.Command) error {
	// 检查是否设置了多个标志
	if cmd.NumFlags() > 1 {
		err := cli.Exit("Only one command can be specified", 1)
		global.Log.Error("Invalid command usage:", zap.Error(err))
		return err
	}
	switch {
	case cmd.Bool(sqlFlag.Name):
		if err := SQL(); err != nil {
			global.Log.Error("Failed to create table structure:", zap.Error(err))
			return err
		}
		global.Log.Info("Successfully created table structure")

	case cmd.Bool(esFlag.Name):
		if err := Elasticsearch(); err != nil {
			global.Log.Error("Failed to create elasticsearch index:", zap.Error(err))
			return err
		}
		global.Log.Info("Successfully created elasticsearch index")
	case cmd.Bool(adminFlag.Name):
		if err := Admin(); err != nil {
			global.Log.Error("Failed to create admin user:", zap.Error(err))
			return err
		}
		global.Log.Info("Successfully to create admin user")
	}
	return nil
}

// NewCmd 创建 CLI 应用
func NewCmd() *cli.Command {
	return &cli.Command{
		Name: "gin Blog",
		Flags: []cli.Flag{
			sqlFlag,
			esFlag,
			adminFlag,
		},
		Action: Run,
	}
}

// InitFlag 初始化并运行 CLI
func InitFlag() {
	if len(os.Args) > 1 {
		cmd := NewCmd()
		err := cmd.Run(context.Background(), os.Args)
		if err != nil {
			global.Log.Error("Application execution encountered an error:", zap.Error(err))
			os.Exit(1)
		}
		if os.Args[1] == "-h" || os.Args[1] == "--help" {
			fmt.Println("Displaying help message...")
		}
		os.Exit(0)
	}
}
